﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using LingDong.HtmlParser;
using System.IO;
using System.Text.RegularExpressions;

namespace LingDong.PictureKeywords
{
    public class Wrapper
    {
        /// <summary>
        /// Get picutre's keywords from a html
        /// A html may contains serval pictures
        /// </summary>
        /// <param name="html"></param>
        /// <returns>a list of [image src, keywords]</returns>
        public static List<KeyValuePair<string, string>> GetPictureKeywords(string url, string html)
        {
            string fileName = Path.GetFileName(url);

            if (fileName.StartsWith("sina"))
                return GetPictureKeywordsSina(html);
            else if (fileName.StartsWith("163"))
                return GetPictureKeywords163(html);
            else if (fileName.StartsWith("ifeng"))
                return GetPictureKeywordsIFent(html);
            else if (fileName.StartsWith("qq"))
                return GetPictureKeywordsQQ(html);
            else
                return new List<KeyValuePair<string, string>>();
        }

        /// <summary>
        /// Designed for sina
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private static List<KeyValuePair<string, string>> GetPictureKeywordsSina(string html)
        {
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                HtmlNode titleNode = doc.DocumentNode.SelectSingleNode("//title");
                string title = titleNode.InnerText.Replace("_新闻中心_新浪网", "");

                HtmlNode containerDiv = doc.DocumentNode.SelectSingleNode("//div[@class='blkContainerSblkCon']");
                HtmlNodeCollection textNodes = containerDiv.SelectNodes("//p");
                string commonContent = textNodes[1].InnerText;

                HtmlNodeCollection imageNodes = containerDiv.SelectNodes("//div[@class='img_wrapper']");
                foreach (HtmlNode node in imageNodes)
                {
                    HtmlNode imageNode = node.SelectSingleNode("img");
                    string src = imageNode.Attributes["src"].Value.Trim();
                    string alt = String.Empty;
                    if (node.Attributes.Contains("alt"))
                        alt = node.Attributes["alt"].Value.Trim();
                    string divDesc = node.InnerText.Trim();
                    string content = RemoveHtmlComment(title + alt + divDesc + commonContent);

                    string singleLineContent = content.Replace("\r\n", "\t").Replace("\n", "\t");
                    result.Add(new KeyValuePair<string, string>(src, singleLineContent));
                }
            }
            catch (Exception)
            {
                return result;
            }
            return result;
        }

        private static List<KeyValuePair<string, string>> GetPictureKeywords163(string html)
        {
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
            return result;
        }

        private static List<KeyValuePair<string, string>> GetPictureKeywordsIFent(string html)
        {
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
            return result;
        }

        private static List<KeyValuePair<string, string>> GetPictureKeywordsQQ(string html)
        {
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                HtmlNode titleNode = doc.DocumentNode.SelectSingleNode("//title");
                string title = titleNode.InnerText.Replace("_新闻_腾讯网", "");

                HtmlNode containerDiv = doc.DocumentNode.SelectSingleNode("//div[@id='ArticleCnt']");
                if (containerDiv == null)
                    containerDiv = doc.DocumentNode.SelectSingleNode("//div[@id='Cnt-Main-Article-QQ']");
                if (containerDiv == null)
                    return new List<KeyValuePair<string,string>>();

                HtmlNodeCollection textNodes = containerDiv.SelectNodes("//p");
                StringBuilder commonContent = new StringBuilder();
                foreach (HtmlNode node in textNodes)
                {
                    commonContent.Append(node.InnerText.Trim());
                    if (commonContent.Length >= Settings.MinCommonTextLen)
                        break;
                }

                string aa = RemoveHtmlComment("aaaa<!--asdfsdfkk-->");

                HtmlNodeCollection imageNodes = containerDiv.SelectNodes("//img[@src]");
                foreach (HtmlNode node in imageNodes)
                {
                    if (!node.XPath.Contains(containerDiv.XPath))
                        continue;

                    string src = node.Attributes["src"].Value.Trim();
                    string alt = String.Empty;
                    if (node.Attributes.Contains("alt"))
                        alt = node.Attributes["alt"].Value.Trim();
                    string divDesc = node.InnerText.Trim();
                    string nextSentece = GetNextSentece(node);

                    string content = RemoveHtmlComment(title + alt + nextSentece + divDesc + commonContent.ToString());                    
                    string singleLineContent = content.Replace("\r\n", "\t").Replace("\n", "\t");
                    result.Add(new KeyValuePair<string, string>(src, singleLineContent));
                }
            }
            catch (Exception)
            {
                return result;
            }
            return result;
        }

        private static string GetNextSentece(HtmlNode imageNode)
        {
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < Settings.ImageTabSiblingNumber; j++)
                {
                    if (imageNode.NextSibling == null)
                        break;
                    string text = imageNode.NextSibling.InnerText.Trim();
                    if (!String.IsNullOrEmpty(text))
                        return text;
                    imageNode = imageNode.NextSibling;
                }

                // find parent's sibling
                imageNode = imageNode.ParentNode;
            }
            return String.Empty;
        }

        private static string RemoveHtmlComment(string content)
        {
            Regex regex = new Regex("<!--.*-->");
            MatchCollection matches = regex.Matches(content);
            foreach (Match match in matches)
            {
                content = content.Replace(match.Value, "");
            }
            content = content.Replace("\r\n\r\n", "\r\n");
            return content;
        }
    }
}
